package cn.com.okgo.convert;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.com.okgo.callback.HttpCallback;
import okhttp3.Response;

/**
 * Created by luwenlong on 2017/5/18.
 */

public class ImageConver implements Converter<File> {

    private String destFileDir;     //目标文件存储的文件夹路径
    private String destFileName;    //目标文件存储的文件名
    private HttpCallback callback;    //下载回调


    public ImageConver(String destFileDir, String destFileName) {
        this.destFileDir = destFileDir;
        this.destFileName = destFileName;
    }

    @Override
    public File convertSuccess(Response response) throws Exception {
        FileOutputStream fos = null;
        File dir = new File(destFileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, destFileName);
        try {
            Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
        } catch (Exception e) {
            file.delete();
            throw new Exception(e);
        } finally {
            response.body().close();
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
}
